package com.huahai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huahai.common.BaseResponse;
import com.huahai.common.ErrorCode;
import com.huahai.common.ResultUtils;
import com.huahai.exception.BusinessException;
import com.huahai.pojo.dto.UserLoginDTO;
import com.huahai.pojo.dto.UserRegisterDTO;
import com.huahai.pojo.dto.UserUpdateDTO;
import com.huahai.pojo.entity.User;
import com.huahai.pojo.vo.UserCurrentVO;
import com.huahai.pojo.vo.UserShowInfoVO;
import com.huahai.pojo.vo.UserVO;
import com.huahai.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.huahai.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = {"http://localhost:5173/"})
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     *
     * @param UserRegisterDTO
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterDTO UserRegisterDTO) {
        // 校验
        if (UserRegisterDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = UserRegisterDTO.getUserAccount();
        String userPassword = UserRegisterDTO.getUserPassword();
        String checkPassword = UserRegisterDTO.getCheckPassword();
        String planetCode = UserRegisterDTO.getPlanetCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param UserLoginDTO
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginDTO UserLoginDTO, HttpServletRequest request) {
        if (UserLoginDTO == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = UserLoginDTO.getUserAccount();
        String userPassword = UserLoginDTO.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前用户
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<UserCurrentVO> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        long userId = currentUser.getId();
        // TODO 校验用户是否合法
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        UserCurrentVO userCurrentVO = new UserCurrentVO();
        BeanUtils.copyProperties(safetyUser, userCurrentVO);
        return ResultUtils.success(userCurrentVO);
    }

    /**
     * 根据用户名批量查找用户信息
     *
     * @param username
     * @param request
     * @return
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "缺少管理员权限");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    /**
     * 根据用户id删除用户信息
     *
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }


    /**
     * 跟据标签查询用户列表
     *
     * @return
     */
    @GetMapping("/search/tags")
    public BaseResponse<List<UserVO>> queryUsersByTags(
            @RequestParam(required = false) List<String> tagNameList, long pageIndex, long pageSize, HttpServletRequest request) {
        List<UserVO> userList = userService.queryUsersByTags(tagNameList, pageIndex, pageSize, request);
        return ResultUtils.success(userList);
    }

    /**
     * 更新用户信息
     *
     * @param userUpdateDTO
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Integer> updateUserInfo(@RequestBody UserUpdateDTO userUpdateDTO, HttpServletRequest request) {
        // 校验用户是否为空
        if (userUpdateDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登陆用户
        User currentUser = userService.getCurrentUser(request);
        int result = userService.updateUserInfo(userUpdateDTO, currentUser);
        return ResultUtils.success(result);
    }

    /**
     * 主页推荐页面展示 - 分页查询
     *
     * @param pageIndex
     * @param pageSize
     * @param request
     * @return
     */
    @GetMapping("/recommend")
    public BaseResponse<Page<User>> searchUsersRecommend(long pageIndex, long pageSize, HttpServletRequest request) {
        // 查询主页推荐的用户信息
        if (pageIndex <= 0 || pageSize <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<User> userList = userService.searchUsersRecommend(pageIndex, pageSize, request);
        return ResultUtils.success(userList);
    }

    /**
     * 获取前num条匹配的用户信息推荐
     * @param num
     * @param request
     * @return
     */
    @GetMapping("/matches")
    public BaseResponse<List<UserVO>> matchesTopNum(Long num, HttpServletRequest request) {
        // 查询主页推荐的用户信息
        if (num < 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登录用户
        User loginUser = userService.getCurrentUser(request);
        List<UserVO> userList = userService.matchesTopNum(num, loginUser);
        return ResultUtils.success(userList);
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @GetMapping("/list/{id}")
    public BaseResponse<UserShowInfoVO> getUserById(@PathVariable("id") Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "用户不存在");
        }
        UserShowInfoVO userShowInfoVO = new UserShowInfoVO();
        BeanUtils.copyProperties(user, userShowInfoVO);
        return ResultUtils.success(userShowInfoVO);
    }



}
